package com.blueocean_health.care.management.appender;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.blueocean_health.care.management.exception.OrderException;
import com.blueocean_health.care.management.exception.OrderServiceException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import com.blueocean_health.care.management.controller.TestController;
import com.blueocean_health.care.management.domain.base.SysResult;

/** 全局异常catch处理类--  处理500 */
@ControllerAdvice
public class GlobalExceptionHandler {
	
	@Value("${sys.debug}")
	private boolean debug;
	private Logger logger = Logger.getLogger(GlobalExceptionHandler.class); 
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public SysResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
		List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
		Set<String> errorSet = new HashSet<String>();
		for (FieldError error : fieldErrors) {
			errorSet.add(error.getDefaultMessage());
		}
		return SysResult.error("请填写字段："+errorSet);
	}
	
	@ExceptionHandler(MultipartException.class)
	@ResponseBody
	public SysResult handleMultipartException(MultipartException ex) {
		if(debug) {
			ex.printStackTrace();
		}
		return SysResult.error("超过最大上传文件限制");
	}


	@ExceptionHandler(OrderException.class)
	@ResponseBody
	public SysResult handleProjectException(OrderException ex) {
		return SysResult.error(ex.getMessage());
	}

	@ExceptionHandler(OrderServiceException.class)
	@ResponseBody
	public SysResult handleProjectException(OrderServiceException ex) {
		return SysResult.error(ex.getMessage());
	}
	
//	@ExceptionHandler(IllegalArgumentException.class)
	@ResponseBody
	public SysResult hanleIllegalArgumentException(IllegalArgumentException ex) {
		if(debug) {
			ex.printStackTrace();
		}
		return SysResult.error(ex.getMessage());
	}
	
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public SysResult handlerException(Exception ex){
		logger.error("错误信息： "+ex.getMessage(),ex);
		System.out.println("错误信息： "+ex.getMessage());
		StackTraceElement[] stackTrace = ex.getStackTrace();
		for (StackTraceElement stackTraceElement : stackTrace) {
			System.out.println("------- "+stackTraceElement);
			//logger.error("------- "+stackTraceElement);
		}
		if(debug){
		ex.printStackTrace();
			return SysResult.error(ex.getMessage());
		}
		
		return SysResult.error();
	}
	
}
